import bjsos
from gksl import GKSLConnection

class GKManagementServiceError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class GKManagementService(object):
    def __init__(self, host, port, kpid, static_priv_key, static_pub_key, server_pub_key):
        self.gksl_conn = GKSLConnection(host, port, 1, kpid, static_priv_key,
                                              static_pub_key, server_pub_key)

    def do_mgmt_call(self, method, params):
        req = bjsos.dumps([u'', method, params], enable_blobs=True)

        self.gksl_conn.connect()
        self.gksl_conn.init_session()

        res = bjsos.loads(self.gksl_conn.do_app_req(req))

        self.gksl_conn.terminate_session()
        self.gksl_conn.disconnect()

        return res

    ###########################################################################
    ### PUBLIC API

    def upload_new_keypair(self, timeout, clnt_pub_key, fallback_kpid=None, server_priv_key=None,
                       server_pub_key=None):
        params = {u'timeout': timeout,
                  u'clnt_pub_key': clnt_pub_key
        }

        if fallback_kpid is not None:
            params[u'fallback_kpid'] = fallback_kpid
        elif server_priv_key is not None and server_pub_key is not None:
            params[u'server_private_key'] = server_priv_key
            params[u'server_public_key'] = server_pub_key
        else:
            raise GKManagementServiceError('missing parameters')

        return self.do_mgmt_call(u'keypair_add', params)

###############################################################################
# EOF
